package com.rainripple.java.starter.code.web;

import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.List;

import javax.validation.Valid;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.rainripple.java.common.dao.IDao;
import com.rainripple.java.starter.code.dto.CodeDto;
import com.rainripple.java.starter.code.entity.Code;
import com.rainripple.java.starter.code.service.CodeService;

@Controller
@RequestMapping(value = "/code")
public class CodeController {

	@Autowired
	private CodeService codeService;

	@RequestMapping(value = { "list", "" })
	public String list(Model model) {
		List<Code> codes = codeService.getAll();
		model.addAttribute("codes", codes);
		return "code/codeList";
	}

	@RequestMapping(value = "get/{id}")
	public String get(@PathVariable Long id, Model model) {
		Code code = codeService.get(id);
		model.addAttribute("code", code);
		return "code/codeView";
	}

	@ModelAttribute("codeDto")
	public CodeDto createCodeDto() {
		return new CodeDto();
	}

	@RequestMapping("add")
	public String form() {
		return "code/codeForm";
	}

	@RequestMapping("save")
	public String processSubmit(@Valid CodeDto codeDto, BindingResult result,
			Model model) {
		Code code = new Code();
		code.setDate(new Date());
		if (result.hasErrors()) {
			return "code/codeForm";
		}
		try {
			BeanUtils.copyProperties(code, codeDto);
			codeService.save(code);
		} catch (IllegalAccessException e) {
			return "code/codeForm";
		} catch (InvocationTargetException e) {
			return "code/codeForm";
		}
		return "redirect:/code/list";
	}
}
